/**
 * 测试circle
 **/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include "../src/lib/circle.h"

circleQueue* _circle;

typedef struct user {
    int id;
    char name[20];
} user;

void produce (void* data, void **value) {

    /* 此种情况是在初始thread的value时出现 */
    if (data == NULL) {
        (*value) = malloc(sizeof(user));
        return;
    }

    /* 初始节点的value指针 */
    if ((*value) == NULL) {
        (*value) = malloc(sizeof(user));
    }

    /* 修改value */
    int i = *((int*) data);
    user* u = (user*) (*value);

    u->id = i;
    sprintf(u->name, "name %d", i);
    printf("[produce]: produce user, id: %d, name: %s\n", u->id, u->name);
}

void consume (void* value) {
    user* u = (user*) value;
    printf("[consume]: find user, id: %d, name: %s\n", u->id, u->name);
    sleep(3);
}

int main(int argc, char* argv[])
{
    _circle = circleCreate();

    circleSetFreeMethod(_circle, free);
    circleSetProduceMethod(_circle, produce);
    circleSetConsumeMethod(_circle, consume);

    circleAddConsumer(_circle);
    circleAddConsumer(_circle);

    circleLoop(_circle);

    int n = 0;
    while (n < 20) {
        circlePushIn(_circle, &n);
        sleep(1);
        n++;
    }

    circleQuit(_circle);
    circleRelease(_circle);
}
